#include "historyrecorditem.h"
#include "ui_historyrecorditem.h"
#include <QDateTime>
#include <QPainter>
#include <QEnterEvent>
#include <QDesktopServices>
#include <qfileinfo.h>
#include "web/tcpmgr.h"
#include "web/file_upload.pb.h"

HistoryRecordItem::HistoryRecordItem(QWidget *parent,
                                     HistoryItemInfo info)
    : QWidget(parent)
    , ui(new Ui::HistoryRecordItem)
    , m_recordFileInfo(info)
{
    ui->setupUi(this);
    ui->CheckBox->setText(m_recordFileInfo.processType);
    //ui->FileTypePLabel->setText(m_recordFileInfo.processType);
    ui->FileNameLabel->setText(m_recordFileInfo.logicalName);
    ui->SizeLabel->setText(formatFileSize(m_recordFileInfo.fileSize));
    ui->DateLabel->setText(m_recordFileInfo.uploadTime.toString("yyyy 年MM月dd日 hh:mm:ss"));

    // 设置初始选中状态
    ui->CheckBox->setChecked(m_isSelected);
}

HistoryRecordItem::~HistoryRecordItem()
{
    delete ui;
}

void HistoryRecordItem::setSelected(bool selected)
{
    if (m_isSelected != selected) {
        m_isSelected = selected;
        ui->CheckBox->setChecked(selected);
        emit selectionChanged(selected);
    }
}



void HistoryRecordItem::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    // 根据悬浮状态选择颜色
    QColor bgColor = m_isHovered ? QColor(0xf8, 0xf8, 0xf8) : QColor(255, 255, 255);
    painter.fillRect(rect(),  bgColor);

    QWidget::paintEvent(event);
}

void HistoryRecordItem::enterEvent(QEnterEvent *event)
{
    m_isHovered = true;
    update();  // 触发重绘
    QWidget::enterEvent(event);
}

void HistoryRecordItem::leaveEvent(QEvent *event)
{
    m_isHovered = false;
    update();  // 触发重绘
    QWidget::leaveEvent(event);
}

void HistoryRecordItem::on_CheckBox_clicked()
{
    m_isSelected = ui->CheckBox->isChecked();
    emit selectionChanged(m_isSelected);
}

//打开所在文件夹资源管理器
void HistoryRecordItem::on_OpenFileBtn_clicked()
{
    QString path = m_recordFileInfo.storagePath;
    QFileInfo fileInfo(path);
    if (fileInfo.exists())  {
        // 转换为本地文件路径格式
        QUrl url = QUrl::fromLocalFile(fileInfo.isDir()  ? path : fileInfo.path());
        QDesktopServices::openUrl(url);
    } else {
        qDebug() << "Path does not exist:" << path;
    }
}


//文件备份
void HistoryRecordItem::on_BackUpBtn_clicked()
{
    if(m_recordFileInfo.isUploaded){
        //ui提示已上传过
        return;
    }
    // 1. 打开文件并验证
    QFile file(m_recordFileInfo.storagePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "文件打开失败：" << m_recordFileInfo.storagePath;
        return;
    }

    ui->BackUpBtn->setText("上传中...");
    ui->BackUpBtn->setEnabled(false);

    // 2. 计算文件总大小和总切片数
    qint64 totalSize = file.size();
    int lastSeq = (totalSize + MAX_FILE_LEN - 1) / MAX_FILE_LEN;  // 向上取整
    int seq = 1;  // 切片序号（从1开始）

    // 3. 循环读取并发送切片
    while (seq <= lastSeq) {
        // 读取当前切片数据（最后一个切片可能小于切片大小）
        QByteArray sliceData = file.read(MAX_FILE_LEN);
        if (sliceData.isEmpty() && !file.atEnd()) {  // 读取错误
            qDebug() << "切片读取失败，seq：" << seq;
            file.close();
            return;
        }

        // 4. 计算已传输大小（累计值）
        qint64 transSize = (seq - 1) * MAX_FILE_LEN + sliceData.size();
        if (transSize > totalSize) transSize = totalSize;  // 避免超出总大小

        // 5. 填充protobuf请求
        file_upload::FileUploadReq req;
        req.set_from_uid(m_recordFileInfo.userId);
        req.set_logical_name(m_recordFileInfo.logicalName.toUtf8().data());
        req.set_process_type(m_recordFileInfo.processType.toStdString());
        req.set_file_hash(m_recordFileInfo.fileHash.toStdString());
        req.set_file_data(sliceData.data(), sliceData.size());  // 当前切片数据
        req.set_seq(seq);                                       // 当前切片序号
        req.set_last(seq == lastSeq ? 1 : 0);                   // 是否最后一个切片
        req.set_last_seq(lastSeq);                              // 总切片数
        req.set_total_size(totalSize);                          // 文件总大小
        req.set_trans_size(transSize);                          // 已传输大小

        // 6. 序列化并发送（通过TcpMgr）
        QByteArray data(req.SerializeAsString().data(), req.ByteSizeLong());
        emit TcpMgr::GetInstance()->sig_sendUploadRequest(data, m_recordFileInfo);

        seq++;  // 准备下一个切片
        // QThread::msleep(10);  // 可选：控制发送速度，避免拥塞
    }

    file.close();
}



void HistoryRecordItem::on_DeleteBtn_clicked()
{
    emit deleteThisRecord(this);
}

